<?php
/**
 * Created by PhpStorm.
 * User: eddy
 * Date: 2018/3/13
 * Time: 23:03
 */

namespace iBrand\Shop\Backend\Http\Controllers;

use Carbon\Carbon;
use iBrand\Component\Goods\Models\Season;
use iBrand\Shop\Backend\Model\Shop;
use Encore\Admin\Facades\Admin as LaravelAdmin;
use Encore\Admin\Layout\Content;
use iBrand\Shop\Backend\Service\DashboardService;
use iBrand\Store\Backend\Repositories\OrderRepository;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{

    protected $dashboardService;
    protected $orderRepository;

    public function __construct(DashboardService $dashboardService, OrderRepository $orderRepository)
    {
        $this->dashboardService = $dashboardService;
        $this->orderRepository = $orderRepository;
    }

    public function index($shop_id)
    {
        $store = Shop::find($shop_id);
        session(['shop_id' => $shop_id]);
        session(['shop_name' => $store->name]);


        $seasonData = $this->dashboardService->getSeasonData(); //获取当前季节相关数据
        $currentKey = $seasonData['currentKey'];
        $seasons = $seasonData['seasons'];

        $condition = explode('-', $currentKey);
        $stockData = $this->dashboardService->getStockData($shop_id, $condition[0], $condition[1]);
        $weekSale = $this->dashboardService->getWeekSaleData($shop_id);
        $salesCycle = $weekSale == 0 ? 0 : floor($stockData['store_nums'] / $weekSale); //销售周期

        $baseData = $this->dashboardService->getCurrentSaleData($shop_id);  //当天数据

        /*7天数据*/
        $s_now = Carbon::now();
        $s_time = $s_now->startOfDay();

        $e_now = Carbon::now();
        $e_time = $e_now->endOfDay();
        $time = [];
        $where = [];
        $more = [];
        $pay_time = [];

        $where['channel'] = 'shop';
        $where['channel_id'] = session('shop_id');
        $where['status'] = ['>', 0];
        $where['pay_status'] = 1;
        $where['submit_time'] = ['<=', $e_time];
        $time['submit_time'] = ['>=', $s_time];

        $orders = $this->orderRepository->getExportOrdersData($where, 0, $time, $more, $pay_time);
        $total = $orders->sum('total'); //今日已付款金额
        $total = number_format($total, 2, '.', '');

        $sevStartTime = Carbon::now()->subDays(7)->startOfDay();
        $sevEndTime = Carbon::now()->subDays(1)->endOfDay();
        $where['submit_time'] = ['<=', $sevEndTime];
        $time['submit_time'] = ['>=', $sevStartTime];
        $sevOrders = $this->orderRepository->getExportOrdersData($where, 0, $time, $more, $pay_time);

        $sevTotal = $sevOrders->sum('total');  //7天已付款订单金额
        $sevTotal = number_format($sevTotal, 2, '.', '');

        /*7天趋势*/
        $sevenDays = '"' .
            Carbon::now()->subDays(7)->format('Y-m-d') . '","' .
            Carbon::now()->subDays(6)->format('Y-m-d') . '","' .
            Carbon::now()->subDays(5)->format('Y-m-d') . '","' .
            Carbon::now()->subDays(4)->format('Y-m-d') . '","' .
            Carbon::now()->subDays(3)->format('Y-m-d') . '","' .
            Carbon::now()->subDays(2)->format('Y-m-d') . '","' .
            Carbon::now()->subDays(1)->format('Y-m-d') . '"';
        $sevenDaysCount = $sevOrders->where('submit_time', '<', Carbon::now()->subDays(6)->startOfDay())->sum('total') . ',' .
            $sevOrders->where('submit_time', '>=', Carbon::now()->subDays(6)->startOfDay())->where('submit_time', '<', Carbon::now()->subDays(5)->startOfDay())->sum('total') . ',' .
            $sevOrders->where('submit_time', '>=', Carbon::now()->subDays(5)->startOfDay())->where('submit_time', '<', Carbon::now()->subDays(4)->startOfDay())->sum('total') . ',' .
            $sevOrders->where('submit_time', '>=', Carbon::now()->subDays(4)->startOfDay())->where('submit_time', '<', Carbon::now()->subDays(3)->startOfDay())->sum('total') . ',' .
            $sevOrders->where('submit_time', '>=', Carbon::now()->subDays(3)->startOfDay())->where('submit_time', '<', Carbon::now()->subDays(2)->startOfDay())->sum('total') . ',' .
            $sevOrders->where('submit_time', '>=', Carbon::now()->subDays(2)->startOfDay())->where('submit_time', '<', Carbon::now()->subDays(1)->startOfDay())->sum('total') . ',' .
            $sevOrders->where('submit_time', '>=', Carbon::now()->subDays(1)->startOfDay())->where('submit_time', '<', Carbon::now()->startOfDay())->sum('total');


        return LaravelAdmin::content(function (Content $content) use ($store, $baseData, $seasons, $currentKey, $salesCycle, $stockData, $total, $sevTotal, $sevenDays, $sevenDaysCount) {

            $content->header('数据统计');

            if (session()->has('shop_name')) {

                $content->description(session('shop_name'));
            }

            $content->breadcrumb(
                ['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
                ['text' => '数据统计', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '门店列表']

            );

            $content->body(view('shop-backend::dashboard.index', compact('store', 'baseData', 'seasons', 'currentKey', 'salesCycle', 'stockData', 'total', 'sevTotal', 'sevenDays', 'sevenDaysCount')));
        });

    }

    public function getMonthData()
    {
        $shop_id = session('shop_id');
        /*最近12个月数据*/
        $date = array_reverse($this->getLastMonthArea(Carbon::now()->year, Carbon::now()->month, 12, 1));
        $monthList = [];
        $monthTotal = [];
        $checkMonthArray = [];

        foreach ($date as $key => $item) {
            $monthList[] = $item['currentMonth'];
            $checkMonthArray[] = $item['currentMonth'];
        }

        $startMonth = $date[0]['startMonth'];
        $endMonth = $date[11]['endMonth'];

        $monthData = DB::table('el_order')
            ->select(DB::raw('substr(submit_time, 1, 7) as yearmonth, SUM(total) as total'))
            ->where('pay_status', 1)
            ->where('channel', 'shop')
            ->where('channel_id', $shop_id)
            ->whereBetween('submit_time', [$startMonth, $endMonth])
            ->groupBy('yearmonth')
            ->get();

        foreach ($checkMonthArray as $key => $item) {
            $filter = $monthData->filter(function ($value) use ($item) {
                return $value->yearmonth == $item;
            });
            if (count($filter) == 0) {
                $monthTotal[] = 0;
            } else {
                $monthTotal[] = $filter->first()->total / 100;
            }
        }

        /*最近12个月用户数据*/
        $prefix = config('ibrand.app.database.prefix', 'ibrand_');
        $userTable = 'o2o_user_shop';

        $monthUserData = DB::table($userTable)
            ->where('shop_id', $shop_id)
            ->select(DB::raw('substr(created_at, 1, 7) as yearmonth, COUNT(*) as total'))
            ->whereBetween('created_at', [$startMonth, $endMonth])
            ->groupBy('yearmonth')
            ->get();

        $monthUserTotal = [];
        foreach ($checkMonthArray as $key => $item) {
            $filter = $monthUserData->filter(function ($value) use ($item) {
                return $value->yearmonth == $item;
            });
            if (count($filter) == 0) {
                $monthUserTotal[] = 0;
            } else {
                $monthUserTotal[] = $filter->first()->total;
            }
        }

        /*最近30天数据*/
        $daysData = $this->getLastDayArea();
        $dayList = $daysData[0];
        $dayTime = $daysData[1];

        $startDay = $dayTime[0] . ' 00:00:00';
        $endDay = $dayTime[29] . ' 23:59:59';
        $daysOrderData = DB::table('el_order')
            ->select(DB::raw('substr(submit_time, 1, 10) as monthDay, SUM(total) as total'))
            ->where('pay_status', 1)
            ->where('channel', 'shop')
            ->where('channel_id', $shop_id)
            ->whereBetween('submit_time', [$startDay, $endDay])
            ->groupBy('monthDay')
            ->get();

        $daysTotal = [];
        foreach ($dayTime as $item) {
            $filter = $daysOrderData->filter(function ($value) use ($item) {
                return $value->monthDay == $item;
            });
            if (count($filter) == 0) {
                $daysTotal[] = 0;
            } else {
                $daysTotal[] = $filter->first()->total / 100;
            }
        }

        /*最近30天用户数据*/
        $daysUserData = DB::table($userTable)
            ->select(DB::raw('substr(created_at, 1, 10) as monthDay, COUNT(*) as total'))
            ->whereBetween('created_at', [$startDay, $endDay])
            ->where('shop_id', $shop_id)
            ->groupBy('monthDay')
            ->get();

        $daysUserTotal = [];
        foreach ($dayTime as $item) {
            $filter = $daysUserData->filter(function ($value) use ($item) {
                return $value->monthDay == $item;
            });
            if (count($filter) == 0) {
                $daysUserTotal[] = 0;
            } else {
                $daysUserTotal[] = $filter->first()->total;
            }
        }

        return $this->ajaxJson(true, ['monthTotal' => $monthTotal, 'monthList' => $monthList, 'dayList' => $dayList, 'daysTotal' => $daysTotal, 'monthUserTotal' => $monthUserTotal, 'daysUserTotal' => $daysUserTotal]);

    }

    public function getSelectSeasonData()
    {
        $shop_id = session('shop_id');
        $currentKey = request('season');
        $condition = explode('-', $currentKey);
        $stockData = $this->dashboardService->getStockData($shop_id, $condition[0], $condition[1]);
        $weekSale = $this->dashboardService->getWeekSaleData($shop_id);
        $salesCycle = $weekSale == 0 ? 0 : floor($stockData['store_nums'] / $weekSale); //销售周期

        return $this->ajaxJson(true, ['salesCycle' => $salesCycle, 'stock' => $stockData]);
    }

    /**
     * 获取最近12个月
     * @param $year
     * @param $month
     * @param $length
     * @param int $page
     * @return array
     */
    protected function getLastMonthArea($year, $month, $length, $page = 1)
    {
        if (!$page) {
            $page = 1;
        }
        $monthNum = $month + $length - $page * $length;
        $num = 1;
        if ($monthNum < -12) {
            $num = ceil($monthNum / (-12));
        }

        $timeAreaList = [];
        for ($i = 0; $i < $length; $i++) {
            $temMonth = $monthNum - $i;
            $temYear = $year;
            if ($temMonth <= 0) {
                $temYear = $year - $num;
                $temMonth = $temMonth + 12 * $num;
                if ($temMonth <= 0) {
                    $temMonth += 12;
                    $temYear -= 1;
                }
            }

            $startMonth = strtotime($temYear . '-' . $temMonth . '-01');//该月的月初时间戳

            if ($temMonth + 1 > 12) {
                $endMonth = strtotime($temYear + 1 . '-01' . '-01 23:59:59') - 86400;//该月的月末时间戳
            } else {
                $endMonth = strtotime($temYear . '-' . ($temMonth + 1) . '-01 23:59:59') - 86400;//该月的月末时间戳
            }

            $res['startMonth'] = $temYear . '-' . $temMonth . '-01 00:00:00'; //该月的月初格式化时间
            $res['endMonth'] = date('Y-m-d H:i:s', $endMonth);//该月的月末格式化时间
            $res['currentMonth'] = date('Y-m', $endMonth);
            $res['timeArea'] = implode(',', [$startMonth, $endMonth]);//区间时间戳
            $timeAreaList[] = $res;
        }
        return $timeAreaList;
    }

    /**
     * 获取最近30天
     * @return array
     */
    protected function getLastDayArea()
    {
        $day = [];
        $day_time = [];
        for ($i = 30; $i >= 1; $i--) {
            $day[] = date('n-d', time() - 60 * 60 * 24 * $i);
            $day_time[] = date('Y-m-d', time() - 60 * 60 * 24 * $i);
        }
        return [$day, $day_time];
    }
}